﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Admin_Components_OrderRequest_SaleOrderRequestDetail : System.Web.UI.UserControl
{
    DBDataContext db = LINQUtil.GetDBWriteOnly();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {

            string SaleOrderRequestID = "";
            if (Session["SaleOrderRequestID"] != null)
            {
                SaleOrderRequestID = Session["SaleOrderRequestID"].ToString();
                loadData(int.Parse(SaleOrderRequestID));
            }
            else
            {
                Response.Redirect("~/san-pham", true);
            }
            //Session["SaleOrderRequestID"] = null;
            //Session.Remove("SaleOrderRequestID");
        }
    }
    private void loadData(int SaleOrderRequestID)
    {
        try
        {
            var sor = (from a in db.SaleOrderRequests
                       join b in db.Customers on a.CustomerID equals b.ID
                       join c in db.Locations on b.DistrictID equals c.ID
                       join d in db.Locations on b.ProvinceID equals d.ID
                       where a.ID == SaleOrderRequestID
                       select new
                       {
                           b.CustomerName,
                           b.PhoneNumber,
                           Address = a.AddressReceipt + ", " + c.LocationName + ", " + d.LocationName,
                           DateTimeReceipt = a.DateTimeReceipt,
                           a.DiscountAmount,
                           a.ID
                       }).FirstOrDefault();

            if (sor != null)
            {
                lblFullName.Text = sor.CustomerName;
                lblPhoneNumber.Text = sor.PhoneNumber;
                lblAddress.Text = sor.Address;
                lblReceiptTime.Text = sor.DateTimeReceipt.Value.ToString("dd/MM/yyyy HH:mm:ss");

                if (sor.DiscountAmount > 0)
                {
                    divDiscount.InnerText = "Giảm giá: " + String.Format("{0:#,#.##}", sor.DiscountAmount) + " VNĐ";
                }
                else
                {
                    divDiscount.InnerText = "Giảm giá: 0 VNĐ";
                }

                loadProduct(sor.ID, sor.DiscountAmount);
                loadPromotion(sor.ID);
            }
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("-----------------------------");
            ControlUtil.LogError("PaymentSuccess-loadData");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("-----------------------------");
        }
    }
    private void loadProduct(int SaleOrderRequestID, double? DiscountAmount)
    {
        try
        {
            var detail = (from d in db.SaleOrderRequestDetails
                          join p in db.Products on d.ProductID equals p.ID
                          where d.SaleOrderRequestID == SaleOrderRequestID
                          select new
                          {
                              p.ProductName,
                              d.Weight,
                              d.Price,
                              d.Amount
                          }).ToList();

            DataTable dt = detail.ToDataTable();
            var sum = dt.AsEnumerable().Sum(dr => DecimalOrNull(dr["Amount"]));
            sumTotal.InnerText = "Tổng: " + String.Format("{0:#,#.##}", sum) + " VNĐ";

            double Payment = Convert.ToDouble(sum - DecimalOrNull(DiscountAmount));
            sumPayment.InnerText = "Thanh toán: " + String.Format("{0:#,#.##}", Payment) + " VNĐ";

            gvProduct.DataSource = dt;
            gvProduct.DataBind();
        }
        catch (Exception ex)
        {

            ControlUtil.LogError("-----------------------------");
            ControlUtil.LogError("PaymentSuccess-loadProduct");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("-----------------------------");
        }
    }

    private void loadPromotion(int SaleOrderRequestID)
    {
        try
        {
            string urlImage = Utils.getUrlImage();
            var lisrPromotion = (from p in db.SaleOrderRequestPromotions
                                 join a in db.Products on p.ProductID equals a.ID
                                 where p.SaleOrderRequestID == SaleOrderRequestID

                                 orderby p.QuantitySelect descending, p.PromotionRemainQty descending
                                 select new
                                 {
                                     Image = urlImage+a.ImagePath,
                                     ProductName = a.ProductName,
                                     PromotionQuantity = p.PromotionRemainQty,
                                     PromotionQuantitySelect = p.QuantitySelect,
                                     p.Weight
                                 }).ToList();
            gvPromotion.DataSource = lisrPromotion;
            gvPromotion.DataBind();
        }
        catch (Exception ex)
        {

            ControlUtil.LogError("-----------------------------");
            ControlUtil.LogError("PaymentSuccess-loadPromotion");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("-----------------------------");
        }
    }
    private decimal? DecimalOrNull(object val)
    {
        try
        {
            return Convert.ToDecimal(val);
        }
        catch
        {
            return null;
        }
    }

    private int? IntOrNull(object val)
    {
        try
        {
            return Convert.ToInt32(val);
        }
        catch
        {
            return null;
        }
    }
}